"""笔记管理模块的序列化器

基于前端业务需求重构的序列化器。
完全匹配前端字段格式和新的模型结构。
"""

from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import Folder, Note, ShareLink

User = get_user_model()


class FolderSerializer(serializers.ModelSerializer):
    """文件夹序列化器
    
    完全匹配前端Folder接口的序列化器。
    """
    
    children = serializers.SerializerMethodField()
    isExpanded = serializers.BooleanField(default=False, read_only=True)
    
    class Meta:
        model = Folder
        fields = [
            'id', 'name', 'count', 'isDefault', 'isShared', 'parentId', 'sortOrder',
            'children', 'isExpanded', 'shareLink', 'sharePassword',
            'syncStatus', 'serverId', 'createdAt', 'updatedAt'
        ]
        read_only_fields = ['id', 'count', 'createdAt', 'updatedAt']
    
    def get_children(self, obj):
        """获取子文件夹
        
        返回扁平化的子文件夹列表，匹配前端需求。
        """
        # 检查obj是否是模型实例
        if hasattr(obj, 'children'):
            children = obj.children.all().order_by('isDefault', 'sortOrder', 'name')
            return FolderSerializer(children, many=True, context=self.context).data
        return []
    
    def create(self, validated_data):
        """创建文件夹
        
        自动设置创建者。
        """
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)
    
    def validate_name(self, value):
        """验证文件夹名称
        
        确保同一用户下文件夹名称唯一。
        """
        user = self.context['request'].user
        queryset = Folder.objects.filter(name=value, created_by=user)
        
        # 如果是更新操作，排除当前对象
        if self.instance:
            queryset = queryset.exclude(id=self.instance.id)
        
        if queryset.exists():
            raise serializers.ValidationError('该文件夹名称已存在')
        
        return value


class NoteSerializer(serializers.ModelSerializer):
    """笔记序列化器
    
    完全匹配前端Note接口的序列化器。
    """
    
    class Meta:
        model = Note
        fields = [
            'id', 'title', 'content', 'folderId', 'isShared',
            'shareLink', 'sharePassword', 'syncStatus', 'serverId',
            'tags', 'createdAt', 'updatedAt'
        ]
        read_only_fields = ['id']
    
    def create(self, validated_data):
        """创建笔记
        
        自动设置作者和时间。
        """
        validated_data['author'] = self.context['request'].user
        
        # 如果没有设置时间，使用前端格式的当前时间
        if not validated_data.get('createdAt'):
            from datetime import datetime
            now = datetime.now()
            validated_data['createdAt'] = f"{now.year}年{now.month:02d}月{now.day:02d}日 {now.hour:02d}:{now.minute:02d}"
        
        if not validated_data.get('updatedAt'):
            # 使用与createdAt相同的时间格式
            from datetime import datetime
            now = datetime.now()
            validated_data['updatedAt'] = f"{now.year}年{now.month:02d}月{now.day:02d}日 {now.hour:02d}:{now.minute:02d}"
        
        return super().create(validated_data)
    
    def update(self, instance, validated_data):
        """更新笔记
        
        自动更新时间。
        """
        # 如果有任何字段变化，更新时间
        if validated_data:
            from datetime import datetime
            now = datetime.now()
            validated_data['updatedAt'] = f"{now.year}年{now.month:02d}月{now.day:02d}日 {now.hour:02d}:{now.minute:02d}"
        
        return super().update(instance, validated_data)
    
    def validate_folderId(self, value):
        """验证文件夹ID
        
        确保文件夹存在且属于当前用户。
        """
        user = self.context['request'].user
        
        # 允许使用默认文件夹ID（1和2）
        if value in [1, 2]:
            return value
        
        try:
            folder = Folder.objects.get(id=value, created_by=user)
            return value
        except Folder.DoesNotExist:
            raise serializers.ValidationError('指定的文件夹不存在或无权访问')


class ShareLinkSerializer(serializers.ModelSerializer):
    """共享链接序列化器
    
    用于管理共享链接的创建和查看。
    """
    
    class Meta:
        model = ShareLink
        fields = [
            'shareId', 'shareLink', 'resourceType', 'resourceId',
            'password', 'expiresAt', 'accessCount', 'createdAt'
        ]
        read_only_fields = ['shareId', 'shareLink', 'accessCount', 'createdAt']
    
    def create(self, validated_data):
        """创建共享链接
        
        自动生成shareId和shareLink。
        """
        import uuid
        from django.conf import settings
        
        # 生成唯一的共享ID
        share_id = str(uuid.uuid4()).replace('-', '')[:16]
        validated_data['shareId'] = share_id
        
        # 生成完整的共享链接
        base_url = getattr(settings, 'FRONTEND_URL', 'http://localhost:3000')
        validated_data['shareLink'] = f"{base_url}/share/{share_id}"
        
        # 设置创建者
        validated_data['created_by'] = self.context['request'].user
        
        return super().create(validated_data)
    
    def validate(self, data):
        """验证共享链接数据
        
        确保资源存在且属于当前用户。
        """
        user = self.context['request'].user
        resource_type = data['resourceType']
        resource_id = data['resourceId']
        
        if resource_type == 'folder':
            try:
                Folder.objects.get(id=resource_id, created_by=user)
            except Folder.DoesNotExist:
                raise serializers.ValidationError('指定的文件夹不存在或无权访问')
        elif resource_type == 'note':
            try:
                Note.objects.get(id=resource_id, author=user)
            except Note.DoesNotExist:
                raise serializers.ValidationError('指定的笔记不存在或无权访问')
        else:
            raise serializers.ValidationError('不支持的资源类型')
        
        return data


class SyncDataSerializer(serializers.Serializer):
    """同步数据序列化器
    
    用于处理前端发送的同步数据。
    """
    
    client_version = serializers.CharField(max_length=20, required=False)
    device_id = serializers.CharField(max_length=100, required=False)
    last_sync_time = serializers.DateTimeField(required=False, allow_null=True)
    
    # 前端数据格式
    categories = serializers.ListField(
        child=serializers.DictField(),
        required=False,
        default=list
    )
    
    notes = serializers.ListField(
        child=serializers.DictField(),
        required=False,
        default=list
    )
    
    tags = serializers.ListField(
        child=serializers.DictField(),
        required=False,
        default=list
    )
    
    # 待同步更改列表
    pendingChanges = serializers.ListField(
        child=serializers.DictField(),
        required=False,
        default=list,
        help_text='待同步的更改列表'
    )


class SyncResponseSerializer(serializers.Serializer):
    """同步响应序列化器
    
    用于返回同步结果。
    """
    
    session_id = serializers.CharField()
    status = serializers.CharField()
    sync_time = serializers.DateTimeField()
    items_uploaded = serializers.IntegerField()
    items_downloaded = serializers.IntegerField()
    conflicts_detected = serializers.IntegerField()
    
    # 返回的数据
    notes = serializers.ListField(child=serializers.DictField())
    categories = serializers.ListField(child=serializers.DictField())
    tags = serializers.ListField(child=serializers.DictField())
    conflicts = serializers.ListField(child=serializers.DictField())


class FolderCreateSerializer(serializers.ModelSerializer):
    """文件夹创建序列化器
    
    专门用于创建文件夹的序列化器，返回完整数据格式。
    """
    
    children = serializers.SerializerMethodField()
    isExpanded = serializers.BooleanField(default=False, read_only=True)
    
    class Meta:
        model = Folder
        fields = [
            'id', 'name', 'count', 'isDefault', 'isShared', 'parentId',
            'children', 'isExpanded', 'shareLink', 'sharePassword',
            'syncStatus', 'serverId', 'createdAt', 'updatedAt'
        ]
        read_only_fields = ['id', 'count', 'createdAt', 'updatedAt']
    
    def get_children(self, obj):
        """获取子文件夹"""
        return []
    
    def create(self, validated_data):
        """创建文件夹"""
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)


class NoteCreateSerializer(serializers.ModelSerializer):
    """笔记创建序列化器
    
    专门用于创建笔记的简化序列化器。
    """
    
    class Meta:
        model = Note
        fields = ['title', 'content', 'folderId', 'tags']
    
    def create(self, validated_data):
        """创建笔记"""
        validated_data['author'] = self.context['request'].user
        
        # 设置创建时间
        from datetime import datetime
        now = datetime.now()
        validated_data['createdAt'] = f"{now.year}年{now.month:02d}月{now.day:02d}日 {now.hour:02d}:{now.minute:02d}"
        
        # 设置更新时间（与创建时间相同）
        validated_data['updatedAt'] = f"{now.year}年{now.month:02d}月{now.day:02d}日 {now.hour:02d}:{now.minute:02d}"
        
        return super().create(validated_data)


class NoteUpdateSerializer(serializers.ModelSerializer):
    """笔记更新序列化器
    
    专门用于更新笔记的序列化器。
    """
    
    class Meta:
        model = Note
        fields = ['title', 'content', 'folderId', 'tags', 'isShared']
    
    def update(self, instance, validated_data):
        """更新笔记"""
        # 如果有任何字段变化，更新时间
        if validated_data:
            from datetime import datetime
            now = datetime.now()
            validated_data['updatedAt'] = f"{now.year}年{now.month:02d}月{now.day:02d}日 {now.hour:02d}:{now.minute:02d}"
        
        return super().update(instance, validated_data)


class SharedContentSerializer(serializers.Serializer):
    """共享内容序列化器
    
    用于返回共享的内容。
    """
    
    resourceType = serializers.CharField()
    resourceId = serializers.IntegerField()
    title = serializers.CharField()
    content = serializers.CharField(required=False)
    author = serializers.CharField()
    createdAt = serializers.CharField()
    updatedAt = serializers.CharField()
    
    # 如果是文件夹，包含笔记列表
    notes = serializers.ListField(
        child=serializers.DictField(),
        required=False
    )